/** @format */

import crypto from "crypto-js"
import { Base64 } from "js-base64"
import {Events} from '../../serve/common'
// yuanbin 20240514 暂时注释掉， 待后续优化
// import { navTo } from '../common.js'

import {
	addTripThrough,getOSSData
} from "../../serve/api"

// 计算签名。
function computeSignature(accessKeySecret, canonicalString) {
	return crypto.enc.Base64.stringify(
		crypto.HmacSHA1(canonicalString, accessKeySecret)
	)
}

 const formatDate = (date) => {
	let taskStartTime = ""
	if (date.getMonth() < 9) {
		taskStartTime = date.getFullYear() + "0" + (date.getMonth() + 1)
	} else {
		taskStartTime = date.getFullYear() + "" + (date.getMonth() + 1)
	}
	if (date.getDate() < 10) {
		taskStartTime += "0" + date.getDate()
	} else {
		taskStartTime += date.getDate()
	}
	return taskStartTime
}

const date = new Date()
date.setHours(date.getHours() + 1)
const policyText = {
	expiration: date.toISOString(), // 设置policy过期时间。
	conditions: [
		// 限制上传大小。
		["content-length-range", 0, 1024 * 1024 * 1024],
	],
}

const getFormDataParams = async (hostUrl) => {
	const result = await getOSSData(
		hostUrl === "https://vtrip-media-edit.oss-cn-shanghai.aliyuncs.com"
			? "vtrip-media-edit"
			: "vtrip-media"
	)
	const { data } = result
	if (!data) {
		const result = {
			OSSAccessKeyId: "",
			signature: "",
			policy: "",
			securityToken: "",
			tempRootDirectory: "",
		}
		return result
	}
	const { accessKeyId, securityToken, tempRootDirectory } = data
	const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
	const signature = computeSignature(data.accessKeySecret, policy)
	const formData = {
		OSSAccessKeyId: accessKeyId,
		signature,
		policy,
		securityToken,
		tempRootDirectory,
		success_action_status: 200,
	}
	return formData
}

export const upload = async (
	mediaFile,
	hostUrl,
	isCamera
) => {
	let filePath = ""
	if (isCamera) {
		filePath = mediaFile.tempFilePath
	} else {
		// #ifdef MP-TOUTIAO
		filePath = mediaFile.path
		// #endif
		// #ifndef MP-TOUTIAO
		filePath = mediaFile.tempFilePath
		// #endif
	}
	const host = hostUrl || "https://vtrip-media.oss-cn-shenzhen.aliyuncs.com"
	const ossObject = await getFormDataParams(host)
	const { tempRootDirectory } = ossObject
	const signature = ossObject.signature
	const ossAccessKeyId = ossObject.OSSAccessKeyId
	const policy = ossObject.policy
	const suffix = filePath.slice(filePath.lastIndexOf("."))
	let nowData = new Date()
	const key = `${tempRootDirectory}${formatDate(
		nowData
	)}/${nowData.getTime()}${suffix}`
	const securityToken = ossObject.securityToken
	return new Promise((resolved, rejected) => {
		uni.uploadFile({
			url: host, // 开发者服务器的URL。
			filePath: filePath,
			name: "file", // 必须填file。
			formData: {
				key,
				policy,
				OSSAccessKeyId: ossAccessKeyId,
				signature,
				"x-oss-security-token": securityToken, // 使用STS签名时必传。
			},
			success: (res) => {
				if (res.statusCode === 204) {
					console.log(res,'55555555',`${host}/${key}`)
					resolved(`${host}/${key}`)
				}
			},
			fail: (err) => {},
		})
	})
}


const getNewFormDataParams = async (bucket) => {
	const result = await getOSSData(
		bucket || "vtrip-media"
	)
	const { data } = result
	if (!data) {
		const result = {
			OSSAccessKeyId: "",
			signature: "",
			policy: "",
			securityToken: "",
			tempRootDirectory: "",
		}
		return result
	}
	const { accessKeyId, securityToken, tempRootDirectory, cdnDomainName  } = data
	const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
	const signature = computeSignature(data.accessKeySecret, policy)
	const formData = {
		OSSAccessKeyId: accessKeyId,
		signature,
		policy,
		securityToken,
		tempRootDirectory,
		cdnDomainName,
		success_action_status: 200,
	}
	return formData
}

export const newUpload = async (
	mediaFile,
	paramsBucket,
	isCamera
) => {
	let filePath = ""
	if (isCamera) {
		filePath = mediaFile.tempFilePath
	} else {
		// #ifdef MP-TOUTIAO
		filePath = mediaFile.path
		// #endif
		// #ifndef MP-TOUTIAO
		filePath = mediaFile.tempFilePath
		// #endif
	}
	const bucket = paramsBucket
	const ossObject = await getNewFormDataParams(bucket)
	const { tempRootDirectory } = ossObject
	const signature = ossObject.signature
	const ossAccessKeyId = ossObject.OSSAccessKeyId
	const policy = ossObject.policy
	const suffix = filePath.slice(filePath.lastIndexOf("."))
	const host = ossObject.cdnDomainName
	let nowData = new Date()
	const key = `${tempRootDirectory}${formatDate(
		nowData
	)}/${nowData.getTime()}${suffix}`
	const securityToken = ossObject.securityToken
	return new Promise((resolved, rejected) => {
		uni.uploadFile({
			url: host, // 开发者服务器的URL。
			filePath: filePath,
			name: "file", // 必须填file。
			formData: {
				key,
				policy,
				OSSAccessKeyId: ossAccessKeyId,
				signature,
				"x-oss-security-token": securityToken, // 使用STS签名时必传。
			},
			success: (res) => {
				if (res.statusCode === 204) {
					console.log(res,'55555555',`${host}/${key}`)
					resolved(`${host}/${key}`)
				}
			},
			fail: (err) => {},
		})
	})
}

// 穿越旅行-上传并检测
export const uploadPhoto = async (
	file,
	videoId,
	isCamera,
	video,
	url,
) => {
	if (!videoId) return
	// let res
	// if(file.tempFilePath || file.path) {
	// 	res = await upload(
	// 		file,
	// 		"https://vtrip-media-edit.oss-cn-shanghai.aliyuncs.com",
	// 		isCamera
	// 	)
	// }
	// let videoOss
	// if (video) {
	// 	videoOss = await upload(
	// 		{
	// 			path: video.path,
	// 			mediaType: "video",
	// 			ossUrl: "",
	// 			duration: 0,
	// 			height: 0,
	// 			size: 0,
	// 			tempFilePath: video.path,
	// 			thumbTempFilePath: "",
	// 			width: 0,
	// 		},
	// 		"https://vtrip-media-edit.oss-cn-shanghai.aliyuncs.com"
	// 	)
	// }
	const result = await addTripThrough({
		// photoUrl: res ? res : videoOss + '?x-oss-process=video/snapshot,t_0,f_jpg,m_fast',
		photoUrl: url,
		sceneId: videoId,
		// materialType: videoOss ? 1 : 2,
		materialType: 2,
		// videoDuration: (video && video.duration) || '',
		// videoUrl: videoOss,
	}).catch((error) => {
		console.log(error,'444444')
		uni.showModal({
			title: "提示",
			content: error,
			showCancel: isCamera || false,
			confirmText: isCamera ? "重新拍摄" : "知道了",
			confirmColor: "#7696FF",
			success: () => {
				if (isCamera) {
					uni.$emit(Events.againTakePhotoEvent)
				}
			},
		})
		return false
	})
	if(!result.success){
		console.log(result,'99999')
		uni.showModal({
			title: "提示",
			content: result.errMsg,
			showCancel: isCamera || false,
			confirmText: isCamera ? "重新拍摄" : "知道了",
			confirmColor: "#F75D1F",
			success: () => {
				if (isCamera) {
					uni.$emit(Events.againTakePhotoEvent)
				}
			},
		})
		uni.hideLoading()
		return
	}
	if (result) {
		const res = result
        // yuanbin 20240514 暂时注释掉， 待后续优化
		// navTo(
		// 	'/packageUserCenter/pages/aigc/traversingLoading/traversingLoding', {
		// 		videoId: res.data
		// },"redirectTo")
	
	}
	uni.hideLoading()
}


